package com.godyao.mall.seckill.controller.front;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.godyao.mall.core.model.ResultCode;
import com.godyao.mall.core.model.ResultMsg;
import com.godyao.mall.seckill.model.req.SeckillActivityReq;
import com.godyao.mall.seckill.service.ISeckillService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author godyao
 * @date 2022/4/1
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/front")
public class SeckillFrontController {
    private final ISeckillService seckillService;

    @GetMapping("/seckillActivity")
    public ResultMsg findAll(@RequestBody SeckillActivityReq seckillActivityReq) {
        Assert.notNull(seckillActivityReq, "请求参数不能为空");
        final Specification<Object> specification = (root, query, criteriaBuilder) -> {
            final List<Predicate> predicates = new ArrayList<>();
            if (StrUtil.isNotBlank(seckillActivityReq.getGoodsName())) {
                final Predicate likeGoodsName = criteriaBuilder.like(root.get("goodsName").as(String.class), "%" + seckillActivityReq.getGoodsName() + "%");
                predicates.add(likeGoodsName);
            }
            return criteriaBuilder.and(ArrayUtil.toArray(predicates, Predicate.class));
        };
        return ResultMsg.resultSuccess( seckillService.findFrontAll(specification, PageRequest.of(seckillActivityReq.getPageNumber()-1, seckillActivityReq.getPageSize())));
    }

    /**
     * 获取系统服务器时间
     * @return
     */
    @GetMapping("/getServerTime")
    public ResultMsg getServerTime() {
        return ResultMsg.resultSuccess(DateUtil.now());
    }

    @PostMapping("/seckill/{code}/{goodsId}")
    public ResultMsg buy(@PathVariable String code, @PathVariable Long goodsId) {
        if (!seckillService.checkUrlCode(code, goodsId)) {
            log.info("code:{} 不匹配", code);
            return ResultMsg.result(ResultCode.SECKILL_CODE_INVALID);
        }
        return seckillService.buy(goodsId);
    }

    @GetMapping("/seckill/generateSeckillCode/{goodsId}")
    public ResultMsg generateSeckillCode(@PathVariable Long goodsId) {
        String code = seckillService.generateSecKillCode(goodsId);
        return ResultMsg.resultSuccess(code);
    }


}
